package com.practice.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.practice.reggie.common.R;
import com.practice.reggie.entity.Category;
import com.practice.reggie.service.CategoryService;
import com.practice.reggie.service.impl.serviceImpl.CategoryServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * 新增分类
     * @param category
     */
    @PostMapping
    public R<String> addCategoryByType(@RequestBody Category category){
        boolean save = categoryService.save(category);
        if (save){
            return R.success("新增分类成功！");
        }
        return R.error("新增失败！");
    }

    @GetMapping("/page")
    public R<Page> page(int page,int pageSize){
        //构造分页构造器
        Page<Category> pageI = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        //添加过滤条件
        //添加排序条件
        wrapper.orderByDesc(Category::getUpdateTime);
        //执行查询
        categoryService.page(pageI,wrapper);
        return R.success(pageI);
    }

    @DeleteMapping
    public R<String> delete(Long id){
        //执行查询
//        categoryService.removeById(id);
        categoryService.remove(id);
        return R.success("删除成功！");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Integer type){
        //条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(type != null,Category::getType,type);

        wrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        //执行查询
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

    @PutMapping
    public R<String> update(@RequestBody Category category){
//        //条件构造器
//        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(Category::getId,category.getId());
        //执行查询
        categoryService.updateById(category);
        return R.success("修改成功！");
    }
}
